package model

type Invite struct {
	Id        int
	OpenId    string
	Invite    string
	IsGet     string
	IsGetLast int
	Time      int
}

type InvitePacket struct {
	Id      int
	OpenId  string
	Invite  string
	Amount  int
	GetTime int
	Time    int
}

type PowerGet struct {
	OpenId string `json:"uniqueid"`
	Id     int    `json:"id"`
}

func InviteCreate(u *Invite) (err error) {
	sql := "INSERT INTO card_packet (open_id, time) VALUES (?, ?)"
	stmt, err := Db.Prepare(sql)
	if err != nil {
		return
	}
	defer stmt.Close()

	res, err := stmt.Exec(u.OpenId, u.Time)
	if err != nil {
		return
	}
	id, err := res.LastInsertId()
	if err != nil {
		return
	}
	u.Id = int(id)
	return nil
}

func InvitePacketCreate(u *InvitePacket) (err error) {
	sql := "INSERT INTO invite_packet (open_id, invite_id, amount, time) VALUES (?, ?, ?, ?)"
	stmt, err := Db.Prepare(sql)
	if err != nil {
		return
	}
	defer stmt.Close()

	res, err := stmt.Exec(u.OpenId, u.Invite, u.Amount, u.Time)
	if err != nil {
		return
	}
	id, err := res.LastInsertId()
	if err != nil {
		return
	}
	u.Id = int(id)
	return nil
}

func InviteGetById(openId string) (invite Invite, err error) {
	err = Db.QueryRow("SELECT id, open_id, invite, is_get, is_get_last, time FROM card_packet WHERE open_id = ? limit 1", openId).Scan(&invite.Id, &invite.OpenId, &invite.Invite, &invite.IsGet, &invite.IsGetLast, &invite.Time)
	return
}

func InvitePacketGetById(id int) (invite InvitePacket, err error) {
	err = Db.QueryRow("select id, open_id, invite_id, amount, get_time, time from invite_packet WHERE id = ? limit 1", id).Scan(&invite.Id, &invite.OpenId, &invite.Invite, &invite.Amount, &invite.GetTime, &invite.Time)
	return
}

func InviteGetByIdTime(openId string, time int) (invite Invite, err error) {
	err = Db.QueryRow("SELECT id, open_id, invite, is_get, is_get_last, time FROM card_packet WHERE open_id = ? and time = ? limit 1", openId, time).Scan(&invite.Id, &invite.OpenId, &invite.Invite, &invite.IsGet, &invite.IsGetLast, &invite.Time)
	return
}

func InviteUpdateInvite(inviteInfo Invite) (err error) {
	statement := "UPDATE card_packet SET invite = ?, is_get = ?, is_get_last = ?, time = ? WHERE open_id = ?"
	stmt, err := Db.Prepare(statement)
	if err != nil {
		return
	}
	defer stmt.Close()

	_, err = stmt.Exec(inviteInfo.Invite, inviteInfo.IsGet, inviteInfo.IsGetLast, inviteInfo.Time, inviteInfo.OpenId)
	return
}

func InviteUpdate(inviteInfo Invite, key string, val interface{}) (err error) {
	statement := "UPDATE card_packet SET " + key + " = ? WHERE open_id = ?"
	stmt, err := Db.Prepare(statement)
	if err != nil {
		return
	}
	defer stmt.Close()

	_, err = stmt.Exec(val, inviteInfo.OpenId)
	return
}
